<template>
	<view class="container">
		<view class="cart-header">
			<text class="page-title">我的购物车</text>
			<text class="clear-btn" @click="clearCart" v-if="cartList.length > 0">清空购物车</text>
		</view>
		
		<view class="cart-empty" v-if="cartList.length === 0">
			<image src="/static/icons/empty-cart.png" mode="aspectFit" class="empty-icon"></image>
			<text class="empty-text">购物车还是空的</text>
			<button class="go-shopping" @click="goShopping">去逛逛</button>
		</view>
		
		<view class="cart-content" v-else>
			<view class="cart-list">
				<view class="cart-item" v-for="(item, index) in cartList" :key="index">
					<view class="item-select">
						<checkbox :checked="item.selected" @click="toggleSelect(item)" color="#409EFF" />
					</view>
					<view class="item-info">
						<image 
							:src="getImgUrl(item.commodity.image && item.commodity.image.length > 0 ? item.commodity.image[0] : '')" 
							mode="aspectFill" 
							class="item-image"
							@click="viewDetail(item.commodity.id)"
						></image>
						<view class="item-detail">
							<text class="item-name">{{ item.commodity.name }}</text>
							<view class="item-tags" v-if="item.commodity.categoryTag && item.commodity.categoryTag.length > 0">
								<text class="tag" v-for="(tag, tagIndex) in item.commodity.categoryTag" :key="tagIndex">{{ tag }}</text>
							</view>
							<text class="item-price">¥{{ item.commodity.price }}</text>
							<view class="item-quantity">
								<view class="quantity-btn minus" @click="decreaseQuantity(item)">-</view>
								<view class="quantity-num">{{ item.quantity }}</view>
								<view class="quantity-btn plus" @click="increaseQuantity(item, item.commodity.stock)">+</view>
							</view>
						</view>
					</view>
					<view class="item-delete" @click="deleteItem(item)">
						<text class="iconfont icon-delete"></text>
					</view>
				</view>
			</view>
			
			<view class="cart-footer">
				<view class="select-all">
					<checkbox :checked="isAllSelected" @click="toggleSelectAll" color="#409EFF" />
					<text>全选</text>
				</view>
				<view class="total-info">
					<view class="total-price">
						<text>合计：</text>
						<text class="price">¥{{ totalPrice.toFixed(2) }}</text>
					</view>
					<button class="checkout-btn" @click="checkout" :disabled="selectedCount === 0">暂不支持({{ selectedCount }})</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { SERVER_BASE_URL } from '@/utils/request';
import http from '@/utils/request';

export default {
	data() {
		return {
			cartList: [],
			loading: false,
			userId: null
		};
	},
	computed: {
		// 是否全选
		isAllSelected() {
			return this.cartList.length > 0 && this.cartList.every(item => item.selected);
		},
		// 选中的商品数量
		selectedCount() {
			return this.cartList.filter(item => item.selected).length;
		},
		// 总价
		totalPrice() {
			return this.cartList.reduce((total, item) => {
				if (item.selected) {
					return total + item.commodity.price * item.quantity;
				}
				return total;
			}, 0);
		}
	},
	onLoad() {
		// 检查登录状态
		this.checkLoginStatus();
	},
	onShow() {
		// 每次显示页面时刷新数据
		if (this.userId) {
			this.getCartList();
		}
	},
	onPullDownRefresh() {
		this.getCartList();
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 500);
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const userStr = uni.getStorageSync('user');
			if (userStr) {
				try {
					const userInfo = JSON.parse(userStr);
					if (userInfo && userInfo.id) {
						this.userId = userInfo.id;
						this.getCartList();
						return true;
					}
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
			
			return false;
		},
		
		// 获取购物车列表
		async getCartList() {
			if (!this.userId) return;
			
			this.loading = true;
			try {
				const response = await http.get('/cart/list');
				
				if (response.code === 200) {
					this.cartList = response.data || [];
				} else {
					uni.showToast({
						title: response.message || '获取购物车失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取购物车失败:', error);
				uni.showToast({
					title: '获取购物车失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 更新商品数量
		async updateQuantity(id, quantity) {
			if (!this.checkLoginStatus()) return;
			
			try {
				const response = await http.put('/cart/update/quantity', null, {
					params: { id, quantity }
				});
				
				if (response.code !== 200) {
					uni.showToast({
						title: response.message || '更新失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('更新数量失败:', error);
				uni.showToast({
					title: '更新失败',
					icon: 'none'
				});
			}
		},
		
		// 减少数量
		decreaseQuantity(item) {
			if (item.quantity <= 1) return;
			
			const newQuantity = item.quantity - 1;
			item.quantity = newQuantity; // 先更新UI
			this.updateQuantity(item.id, newQuantity);
		},
		
		// 增加数量
		increaseQuantity(item, maxStock) {
			if (maxStock && item.quantity >= maxStock) {
				uni.showToast({
					title: '已达到最大库存',
					icon: 'none'
				});
				return;
			}
			
			const newQuantity = item.quantity + 1;
			item.quantity = newQuantity; // 先更新UI
			this.updateQuantity(item.id, newQuantity);
		},
		
		// 更新选中状态
		async toggleSelect(item) {
			if (!this.checkLoginStatus()) return;
			
			const newSelected = !item.selected;
			item.selected = newSelected; // 先更新UI
			
			try {
				const response = await http.put('/cart/update/selected', null, {
					params: { id: item.id, selected: newSelected }
				});
				
				if (response.code !== 200) {
					// 如果失败，恢复原状态
					item.selected = !newSelected;
					uni.showToast({
						title: response.message || '更新失败',
						icon: 'none'
					});
				}
			} catch (error) {
				// 如果失败，恢复原状态
				item.selected = !newSelected;
				console.error('更新选中状态失败:', error);
				uni.showToast({
					title: '更新失败',
					icon: 'none'
				});
			}
		},
		
		// 全选/取消全选
		async toggleSelectAll() {
			if (!this.checkLoginStatus()) return;
			
			const newSelected = !this.isAllSelected;
			
			// 先更新UI
			this.cartList.forEach(item => {
				item.selected = newSelected;
			});
			
			try {
				const response = await http.put('/cart/update/selected/batch', { selected: newSelected });
				
				if (response.code !== 200) {
					// 如果失败，恢复原状态
					this.cartList.forEach(item => {
						item.selected = !newSelected;
					});
					uni.showToast({
						title: response.message || '更新失败',
						icon: 'none'
					});
				}
			} catch (error) {
				// 如果失败，恢复原状态
				this.cartList.forEach(item => {
					item.selected = !newSelected;
				});
				console.error('更新全选状态失败:', error);
				uni.showToast({
					title: '更新失败',
					icon: 'none'
				});
			}
		},
		
		// 删除购物车商品
		deleteItem(item) {
			if (!this.checkLoginStatus()) return;
			
			uni.showModal({
				title: '提示',
				content: '确定要删除该商品吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.delete('/cart/delete', {
								params: { id: item.id }
							});
							
							if (response.code === 200) {
								// 更新本地数据
								this.cartList = this.cartList.filter(cartItem => cartItem.id !== item.id);
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: response.message || '删除失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('删除失败:', error);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 清空购物车
		clearCart() {
			if (!this.checkLoginStatus()) return;
			
			uni.showModal({
				title: '提示',
				content: '确定要清空购物车吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.delete('/cart/clear');
							
							if (response.code === 200) {
								this.cartList = [];
								uni.showToast({
									title: '清空成功',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: response.message || '清空失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('清空失败:', error);
							uni.showToast({
								title: '清空失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 结算
		checkout() {
			if (!this.checkLoginStatus()) return;
			
			// 显示提示信息
			uni.showToast({
				title: '小程序暂不支持结账',
				icon: 'none',
				duration: 2000
			});
			
			// 以下代码暂时注释，等待小程序支持结账功能时再启用
			/*
			const selectedItems = this.cartList.filter(item => item.selected);
			if (selectedItems.length === 0) {
				uni.showToast({
					title: '请选择要结算的商品',
					icon: 'none'
				});
				return;
			}
			
			// 将选中的商品保存到本地存储，以便结算页面使用
			uni.setStorageSync('checkoutItems', JSON.stringify(selectedItems));
			
			// 跳转到结算页面
			uni.navigateTo({
				url: '/pages/order/checkout'
			});
			*/
		},
		
		// 去购物
		goShopping() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		
		// 查看商品详情
		viewDetail(commodityId) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${commodityId}`
			});
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '/static/icons/default-product.png';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			
			if (url.startsWith('/uploads/')) {
				fullUrl = SERVER_BASE_URL + url;
			}
			
			return fullUrl;
		}
	}
};
</script>

<style>
.container {
	padding-bottom: 100rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 购物车头部 */
.cart-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff;
}

.page-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.clear-btn {
	font-size: 26rpx;
	color: #FF5252;
}

/* 空购物车样式 */
.cart-empty {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-icon {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 30rpx;
	color: #999;
	margin-bottom: 40rpx;
}

.go-shopping {
	width: 240rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	color: #ffffff;
	background-color: #409EFF;
	border-radius: 40rpx;
}

/* 购物车列表样式 */
.cart-list {
	padding: 20rpx;
}

.cart-item {
	display: flex;
	align-items: center;
	padding: 20rpx;
	margin-bottom: 20rpx;
	background-color: #ffffff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.item-select {
	margin-right: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.item-info {
	flex: 1;
	display: flex;
}

.item-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
	background-color: #f5f5f5;
}

.item-detail {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.item-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.item-tags {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 10rpx;
}

.tag {
	font-size: 20rpx;
	color: #409EFF;
	background-color: #ecf5ff;
	padding: 2rpx 10rpx;
	margin-right: 10rpx;
	margin-bottom: 6rpx;
	border-radius: 4rpx;
}

.item-price {
	font-size: 32rpx;
	color: #ff6700;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.item-quantity {
	display: flex;
	align-items: center;
	height: 60rpx;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #f5f5f5;
	font-size: 28rpx;
}

.quantity-btn.minus {
	border-radius: 6rpx 0 0 6rpx;
}

.quantity-btn.plus {
	border-radius: 0 6rpx 6rpx 0;
}

.quantity-num {
	min-width: 80rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	font-size: 28rpx;
	background-color: #f5f5f5;
}

.item-delete {
	padding: 20rpx;
	color: #999;
}

.item-delete .iconfont {
	font-size: 40rpx;
}

/* 底部结算栏样式 */
.cart-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	padding: 0 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.select-all {
	display: flex;
	align-items: center;
	font-size: 28rpx;
	color: #333;
}

.total-info {
	flex: 1;
	display: flex;
	justify-content: flex-end;
	align-items: center;
}

.total-price {
	margin-right: 20rpx;
	font-size: 28rpx;
	color: #333;
}

.price {
	color: #ff6700;
	font-weight: bold;
}

.checkout-btn {
	width: 240rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	color: #ffffff;
	background-color: #409EFF;
	border-radius: 40rpx;
}

.checkout-btn[disabled] {
	background-color: #cccccc;
	color: #ffffff;
}
</style> 